<template>
  <view class="simple-text-editor">
    <textarea
      class="text-area"
      :value="modelValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :maxlength="maxLength"
      :auto-height="autoHeight"
      :focus="autoFocus"
      :cursor-spacing="cursorSpacing"
      :show-confirm-bar="showConfirmBar"
      :adjust-position="adjustPosition"
      :hold-keyboard="holdKeyboard"
      @input="handleInput"
      @focus="handleFocus"
      @blur="handleBlur"
      @confirm="handleConfirm"
      @keyboardheightchange="handleKeyboardHeightChange"
    />
    <view v-if="showCounter" class="character-counter">
      {{ currentCount }}/{{ maxLength }}
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  maxLength: {
    type: Number,
    default: 1000
  },
  autoHeight: {
    type: Boolean,
    default: true
  },
  autoFocus: {
    type: Boolean,
    default: false
  },
  showCounter: {
    type: Boolean,
    default: true
  },
  cursorSpacing: {
    type: Number,
    default: 20
  },
  showConfirmBar: {
    type: Boolean,
    default: true
  },
  adjustPosition: {
    type: Boolean,
    default: true
  },
  holdKeyboard: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits([
  'update:modelValue',
  'focus',
  'blur',
  'confirm',
  'keyboardheightchange'
])

const currentCount = computed(() => props.modelValue.length)

const handleInput = (e) => {
  emit('update:modelValue', e.detail.value)
}

const handleFocus = (e) => {
  emit('focus', e)
}

const handleBlur = (e) => {
  emit('blur', e)
}

const handleConfirm = (e) => {
  emit('confirm', e)
}

const handleKeyboardHeightChange = (e) => {
  emit('keyboardheightchange', e)
}

// 暴露方法
defineExpose({
  focus: () => {
    const query = uni.createSelectorQuery().select('.text-area')
    query.focus().exec()
  },
  blur: () => {
    const query = uni.createSelectorQuery().select('.text-area')
    query.blur().exec()
  }
})
</script>

<style scoped>
.simple-text-editor {
  width: 100%;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background-color: white;
  overflow: hidden;
  transition: all 0.3s ease;
}

.simple-text-editor:active {
  border-color: var(--primary-color);
}

.text-area {
  width: 100%;
  min-height: 120px;
  padding: 12px;
  font-size: 16px;
  line-height: 1.6;
  color: var(--text-primary);
  box-sizing: border-box;
}

.text-area:disabled {
  background-color: #f5f5f5;
  color: var(--text-disabled);
}

.character-counter {
  text-align: right;
  padding: 0 12px 8px;
  font-size: 12px;
  color: var(--text-disabled);
}
</style>